<?php
class ThemesController extends AppController {

	var $name = 'Themes';
	var $uses = array('Theme');

	function admin_index() {
		$this->Theme->recursive = 0;
		$this->set('themes', $this->paginate());
	}

	function admin_switchto($id = null) {
		if($this->Theme->findById($id)) {
			$this->Theme->updateAll(array('active'=>0));
			$this->Theme->updateAll(array('active'=>1),array('id'=>$id));
			$this->Session->setFlash(__('THEME_ACTIVATED_OK',true));
		} else {
			$this->Session->setFlash(__('THEME_ACTIVATED_ERROR',true));
		}
		$this->redirect(array('action'=>'admin_index'));
	}
	
	function admin_add() {
		if (!empty($this->data)) {
			$this->Theme->create();
			if ($this->Theme->save($this->data)) {
				$this->Session->setFlash(__('THEME_SAVED_OK', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('THEME_SAVED_ERROR', true));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$this->Theme->findById($id)) {
			$this->Session->setFlash(__('THEME_INVALID', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Theme->save($this->data)) {
				$this->Session->setFlash(__('THEME_SAVED_OK', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('THEME_SAVED_ERROR', true));
			}
		} else {
			$this->data = $this->Theme->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$this->Theme->findById($id) || ($id==1)) {
			$this->Session->setFlash(__('THEME_INVALID', true));
		}
		if ($this->Theme->del($id)) {
			$this->Session->setFlash(__('THEME_DELETED_OK', true));
		}
		$this->redirect(array('action'=>'index'));
	}

	function admin_editlayout($action = 'layout') {
		uses('file');
		$css = $this->Theme->find('active=1');
		if($action=='layout') {
			$path = '..'.DS.'views'.DS.'themed'.DS.$css['Theme']['folder'].DS.'layouts'.DS.'default.ctp';
		} else {
			$path = 'themed'.DS.$css['Theme']['folder'].DS.'css'.DS.'stylesheet.css';
		}
		if(!empty($this->data)) {
			$f = new File($path);	
			if($f->write($this->data['Theme']['file'],'w',true)) {
				$this->Session->setFlash(__('LAYOUT_EDIT_OK',true));
			} else {
				$this->Session->setFlash(__('LAYOUT_EDIT_ERROR'));
			}
		} else {
			$f = new File($path);
			$this->set('file',$f->read());
		}
		$this->set('action',$action);
	}
}
?>